package a51qindian.com.comprehensive.activity;

import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;

import com.li.interfaces.OnItemClickListener;
import com.li.utils.ToastUtil;
import com.li.widget.DoubleTextView;
import com.li.widget.MultipleLayout;
import com.li.widget.TopNavigationBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import a51qindian.com.comprehensive.Const;
import a51qindian.com.comprehensive.R;
import a51qindian.com.comprehensive.adapter.DeviceAdapter;
import a51qindian.com.comprehensive.base.QDBaseActivity;
import a51qindian.com.comprehensive.items.LinearItemDecoration;
import a51qindian.com.comprehensive.model.CountBaseModel;
import a51qindian.com.comprehensive.model.DeviceInfo;
import a51qindian.com.comprehensive.net.ObservableHelper;
import a51qindian.com.comprehensive.net.RetrofitCreator;
import a51qindian.com.comprehensive.net.SelectorObserver;
import a51qindian.com.comprehensive.util.SpUtil;
import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

/**
 * Author: Li
 * Date: 2017/9/12 0012
 * Description: 商铺设备管理
 */

public class ShopDeviceManagerActivity extends QDBaseActivity {

    @BindView(R.id.top_navigation)
    TopNavigationBar mTopNavigation;
    @BindView(R.id.recycler_device)
    RecyclerView mRecyclerDevice;
    @BindView(R.id.layout_content)
    MultipleLayout mLayoutContent;
    @BindView(R.id.layout_refresh)
    SmartRefreshLayout mLayoutRefresh;
    @BindView(R.id.dtv_num)
    DoubleTextView mDtvNum;
    private List<DeviceInfo> mDeviceInfoList;
    private DeviceAdapter mDeviceAdapter;

    @Override
    protected void initSth() {
        super.initSth();

        mTopNavigation.setNavigationBarListener(this);
        mDeviceAdapter = new DeviceAdapter(this);
        mRecyclerDevice.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerDevice.setAdapter(mDeviceAdapter);
        mRecyclerDevice.addItemDecoration(new LinearItemDecoration());
        mDeviceInfoList = new ArrayList<>();
        getDeviceList(mUid, "0");
        setSmartRefreshLayout(mLayoutRefresh);
        if (SpUtil.getUserInfo(this, SpUtil.USER_GRADE).equals(Const.TYPE_SHOP)) {
            mTopNavigation.setTxtFunctionVisible(View.VISIBLE);
            mTopNavigation.setFunctionTxt("加装申请");
            mDeviceAdapter.setItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(View view, final int pos) {
                    final String deviceId = mDeviceInfoList.get(pos).getSn();
                    AlertDialog.Builder builder = new AlertDialog.Builder(ShopDeviceManagerActivity.this)
                            .setTitle("提示")
                            .setMessage("是否报修设备：" + deviceId)
                            .setNegativeButton("取消", null)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    deviceRepair(mUid, deviceId, pos);
                                }
                            });
                    builder.create().show();
                }
            });
        }
    }

    @Override
    public void onFunctionTxtListener(View view) {
        super.onFunctionTxtListener(view);
        View view1= LayoutInflater.from(mContext).inflate(R.layout.layout_update_dialog,null);
        final EditText editText=view1.findViewById(R.id.et_update);
        editText.setInputType(InputType.TYPE_CLASS_NUMBER);
        editText.setSingleLine(true);
        editText.setHint("输入加装数量");
        AlertDialog.Builder builderCommission = new AlertDialog.Builder(ShopDeviceManagerActivity.this)
                .setTitle("提示")
                .setView(view1)
                .setNegativeButton("取消", null)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String txt=editText.getText().toString();
                        if (TextUtils.isEmpty(txt)||txt.equals("0")) {
                            showToast("输入正确设备数量");
                            return;
                        }
                        shopAddApply(mUid, editText.getText().toString());
                    }
                });
        builderCommission.create().show();
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        super.onRefresh(refreshlayout);
        getDeviceList(mUid, "0");
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        super.onLoadmore(refreshlayout);
        getDeviceList(mUid, String.valueOf(mPage + 1));
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_shop_device_manager;
    }


    /**
     * 获取设备列表
     *
     * @param uid id
     */
    private void getDeviceList(String uid, String page) {
        mLayoutContent.onLoadingWithContent();
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("page", page);
        ObservableHelper.createObservable(RetrofitCreator.createService().deviceList(map))
                .subscribe(new SelectorObserver<CountBaseModel<List<DeviceInfo>>>() {
                    @Override
                    protected void onErrorCodeInfo(int code, String info) {
                        stopRefreshLoad();
                        mLayoutRefresh.setLoadmoreFinished(true);
                        ToastUtil.showToast(ShopDeviceManagerActivity.this, info);
                        mLayoutContent.onSuccess();
                    }

                    @Override
                    protected void onSuccess(CountBaseModel<List<DeviceInfo>> listBaseModel) {
                        List<DeviceInfo> deviceInfoList = listBaseModel.getData();

                        mLayoutContent.onSuccess();

                        if (mIsRefresh) {
                            mPage = 0;
                            mDeviceInfoList.clear();
                            mLayoutRefresh.setLoadmoreFinished(false);
                        } else {
                            mPage++;
                        }
                        stopRefreshLoad();
                        if (!mIsRefresh && deviceInfoList.size() < Const.DEFAULT_PAGE_SIZE) {
                            mLayoutRefresh.setLoadmoreFinished(true);
                        }
                        mDeviceInfoList.addAll(deviceInfoList);
                        mDeviceAdapter.setDeviceInfoList(mDeviceInfoList);
                        mDtvNum.setTxtRight(listBaseModel.getCount());
                    }

                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mLayoutContent.onSuccess();
                        stopRefreshLoad();
                        showToast(e.getMessage());
                    }
                });
    }

    /**
     * 加装
     *
     * @param uid   用户编号
     * @param count 数量  默认为1
     */
    private void shopAddApply(String uid, String count) {
        mLayoutContent.onLoadingWithContent("正在申请");
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("number", count);
        ObservableHelper.createObservable(RetrofitCreator.createService().shopAddApply(map))
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        mLayoutContent.onSuccess();
                        try {
                            JSONObject object = new JSONObject(s);
                            String info = object.getString("info");
                            showToast(info);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mLayoutContent.onSuccess();
                        showToast(e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 设备报修
     * @param uid   用户编号
     * @param sn    设备编号
     * @param pos   位置  刷新界面使用
     */
    private void deviceRepair(String uid, String sn, final int pos) {
        mLayoutContent.onLoadingWithContent("正在报修");
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("sn", sn);
        ObservableHelper.createObservable(RetrofitCreator.createService().deviceRepair(map))
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        mLayoutContent.onSuccess();
                        try {
                            JSONObject object = new JSONObject(s);
                            int code = object.getInt("code");
                            showToast(object.getString("info"));
                            if (code == 1) {
                                mDeviceInfoList.get(pos).setStatus("3");
                                mDeviceAdapter.notifyItemChanged(pos);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mLayoutContent.onSuccess();
                        showToast(e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

}
